<template>
    <div class="graphics">
        <div class="graphicsList" v-show="!editShow">
            <div class="header flexbetween">
                <el-input placeholder="请输入关键字搜索" v-model="keyword" size="small" style="width: 300px">
                    <span slot="suffix" class="iconfont icon-sousuo" @click="filterList"></span>
                </el-input>
                <div class="iconBtn">
                    <el-tooltip effect="light" content="添加" placement="top" :enterable="false" v-if="menuAuthCodes.includes('M161')">
                        <span class="iconfont icon-tianjia" @click="openAdd"></span>
                    </el-tooltip>
                </div>
            </div>
            <element-table :data="graphicsList" :columns="cloumns" :loading="tableLoading" :tableHeight="tableHeight" :pageNo="pageNo"
                           :pageSize="pageSize" :total="total" @changePageNo="changePageNo" @changePageSize="changePageSize">
            </element-table>
        </div>
        <div class="graphicsEdit" v-show="editShow">
            <div v-loading="detailLoading" style="height: 100%">
                <div class="header flexbetween">
                    <span>图文详情</span>
                    <el-button size="small" @click="clearData" plain>返回列表</el-button>
                </div>
                <el-scrollbar style="height: calc(100% - 120px)">
                    <div class="container">
                        <div class="editFrom">
                            <el-form ref="graphicsForm" :model="graphicsFormList[graphicsIndex]" :rules="rules" label-width="90px">
                                <p class="bold mb20" style="padding-left: 15px">基本信息</p>
                                <el-form-item label="分类" required>
                                    <a-tree-select v-model="fromClassId" style="width: 100%" :tree-data="classList" allow-clear
                                                   tree-node-filter-prop="title" placeholder="请选择分类" :replace-fields="replaceFields"
                                                   :dropdown-style="{ maxHeight: '350px', overflow: 'auto' }" treeDefaultExpandAll />
                                </el-form-item>
                                <p class="mb20" style="display: flex;align-items: center;">
                                    <span class="bold" style="padding: 0 20px 0 15px">图文信息</span>
                                    <el-switch v-model="isMulti" :active-value="1" :inactive-value="0"></el-switch>
                                    <span style="color: #363C43;margin-left: 10px">多图文模式</span>
                                </p>
                                <el-form-item label="图文标题" prop="title">
                                    <el-input v-model="graphicsFormList[graphicsIndex].title" size="small"></el-input>
                                </el-form-item>
                                <el-form-item label="摘要">
                                    <el-input size="small" v-model="graphicsFormList[graphicsIndex].digest" placeholder="请输入0-200个字符"
                                              maxlength="200"></el-input>
                                </el-form-item>
                                <el-form-item label="作者">
                                    <el-input size="small" v-model="graphicsFormList[graphicsIndex].author" placeholder="请输入0-16个字符"
                                              maxlength="16"></el-input>
                                </el-form-item>
                                <el-form-item label="原文链接" required class="inlineblock">
                                    <el-switch v-model="graphicsFormList[graphicsIndex].sourceurlStatus" :active-value="1"
                                               :inactive-value="0" @change="clearVal">
                                    </el-switch>
                                </el-form-item>
                                <el-form-item label="" prop="url" class="inlineblock link">
                                    <el-input v-show="graphicsFormList[graphicsIndex].sourceurlStatus == 1"
                                              v-model="graphicsFormList[graphicsIndex].url" size="small" style="width:calc(100% - 40px)">
                                    </el-input>
                                </el-form-item>
                                <el-form-item prop="content" v-show="graphicsFormList[graphicsIndex].sourceurlStatus == 0">
                                    <tinymce v-model="graphicsFormList[graphicsIndex].content" ref="graphicsTinymce"
                                             @change="richTextChange" :height="200"></tinymce>
                                </el-form-item>
                                <el-form-item label="封面设置" prop="picurl" style="margin-bottom: 10px">
                                    <el-button size="small" plain @click="toggleInputClick">本地上传</el-button>
                                    <el-button size="small" plain @click="openPicSelect">图片库上传</el-button>
                                    <div style="color: #90979D;line-height: 30px">推荐尺寸：1000*450</div>
                                    <input type="file" @change="picChange" id="uploadPic" style="display:none" />
                                    <p v-show="graphicsFormList[graphicsIndex].picurl">
                                        <el-image style="width: 200px;"
                                                  :src="graphicsFormList[graphicsIndex].picurl?graphicsFormList[graphicsIndex].picurl:''">
                                        </el-image>
                                        <span class="delPic" @click="delPic">删除</span>
                                    </p>
                                </el-form-item>
                                <el-form-item label="">
                                    <el-switch v-model="graphicsFormList[graphicsIndex].showPic" :active-value="1" :inactive-value="0">
                                    </el-switch>
                                    <span style="color: #676E75;margin-left: 10px">封面在正文中显示</span>
                                    <span class="iconfont icon-yulan"></span>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div class="preview">
                            <p class="bold">效果预览</p>
                            <div :class="['graphicsPreview',{'isMulti': isMulti == 1}]">
                                <div :class="['graphicsItem',{'active': graphicsIndex == i}]" v-for="(item,i) in graphicsFormList" :key="i"
                                     @click="selectGraphics(i)">
                                    <el-image :src="item.picurl?item.picurl:''">
                                        <div slot="error" class="image-slot">
                                            <i class="el-icon-picture-outline"></i>
                                        </div>
                                    </el-image>
                                    <p class="title">{{item.title}}</p>
                                    <span class="delIcon iconfont icon-guanbi2" @click.stop="delGraphics(i)"
                                          v-if="isMulti == 1 && i != 0"></span>
                                </div>
                                <div class="graphicsItem addGraphics" v-show="isMulti == 1">
                                    <span class="iconfont icon-tianjia" @click="addGraphics"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
                <div class="buttomBtn">
                    <el-button size="small" type="primary" class="fl" v-show="editType == 'edit'" @click="prev">上一个</el-button>
                    <el-button size="small" type="primary" class="fl" v-show="editType == 'edit'" @click="next">下一个</el-button>
                    <el-button size="small" type="primary" class="fr" @click="saveValidate">保存</el-button>
                    <el-button size="small" type="danger" plain class="fr" @click="delMessage(editId)" v-show="editType == 'edit'">删除
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 选择图片库 -->
        <el-dialog :visible.sync="picVisible" title="选择素材" width="980px" class="selectPic">
            <el-radio-group v-model="picRadio">
                <div class="picList">
                    <div class="pictureItem" v-for="item in picList" :key="item.id">
                        <el-radio :label="item.url"><span></span></el-radio>
                        <img :src="item.url" />
                    </div>
                </div>
            </el-radio-group>
            <el-empty v-if="picList.length == 0"></el-empty>
            <span slot="footer" class="dialog-footer">
                <el-button @click="picVisible = false" size="small" type="text">取消</el-button>
                <el-button @click="selectPic" type="primary" size="small">保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

import elementTable from "@/components/elementTable";
import Tinymce from "@/components/Tinymce";
import { getMessageList, addMessage, findMessageById, editMessage, delMessage, getFileList } from "@/api/material.js"
import { lingYanUpload } from "@/utils/upload";
export default {
    name: "graphics",
    props: {
        classId: {
            type: String,
        },
        classList: {
            type: Array,
            default: []
        }
    },
    data() {
        var validateLink = (rule, value, callback) => {
            if (!value && this.graphicsForm.sourceurlStatus == "1") {
                callback(new Error('请输入原文链接'));
            } else {
                callback();
            }
        };
        var validateContent = (rule, value, callback) => {
            if (!value && this.graphicsForm.sourceurlStatus == "0") {
                callback(new Error('请输入正文'));
            } else {
                callback();
            }
        };
        return {
            editType: "add",
            editShow: false,
            keyword: "",
            graphicsList: [],
            graphicsIndex: 0,
            tableLoading: false,
            pageNo: 1,
            pageSize: 10,
            total: 0,
            isMulti: 0, //是否开启多图文
            fromClassId: null, //分类ID
            editId: "",
            graphicsFormList: [
                {
                    title: "",
                    digest: "",
                    author: "",
                    sourceurlStatus: 0, //是否开启原文链接
                    url: "",
                    showPic: 0,
                    content: "",
                    picurl: "",
                }
            ],
            rules: {
                title: [{ required: true, message: '请输入图文标题', trigger: 'blur' }],
                picurl: [{ required: true, message: '封面地址不能为空', trigger: 'blur' }],
                url: [{ validator: validateLink, trigger: 'blur' }],
                content: [{ validator: validateContent, trigger: 'blur' }],
            },
            cloumns: [
                {
                    config: {
                        label: "图文标题",
                    },
                    render: (h, scope) => {
                        return (
                            <span>{this.questionTitle(scope.contentList)}</span>
                        );
                    },
                },
                {
                    config: {
                        label: "图文类型",
                    },
                    render: (h, scope) => {
                        return (
                            <span>{scope.isMulti == 1 ? "多图文" : "单图文"}</span>
                        );
                    },
                },
                {
                    config: {
                        label: "分类",
                        prop: "className",
                    }
                },
                {
                    config: {
                        label: "创建时间",
                        prop: "addTime",
                        width: "170"
                    }
                },
                {
                    config: {
                        label: "最后更新时间",
                        prop: "updateTime",
                        width: "170"
                    }
                },
                {
                    config: {
                        label: "操作",
                        width: "100"
                    },
                    render: (h, scope) => {
                        return (
                            <div class="operation">
                                <el-tooltip effect="light" content="编辑" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M162')}>
                                    <span class="iconfont icon-bianjidaan" onClick={() => this.openEdit(scope.id)}></span>
                                </el-tooltip>
                                <el-tooltip effect="light" content="删除" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M163')}>
                                    <span class="iconfont icon-shanchu" onClick={() => this.delMessage(scope.id)}></span>
                                </el-tooltip>
                            </div>
                        );
                    },
                },
            ],
            replaceFields: {
                title: "label",
                value: "id",
                children: 'children',
            },
            picVisible: false,
            picList: [],
            picRadio: "",
            currentIndex: 0,
            detailLoading: false,
        }
    },
    created() {
        this.getMessageList();
    },
    methods: {
        //获取图文列表
        getMessageList(cb) {
            if (!this.menuAuthCodes.includes("M160")) {
                return;
            }
            this.tableLoading = true;
            var param = {
                classId: this.classId,
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                keyword: this.keyword,
            }
            getMessageList(param).then(resp => {
                this.tableLoading = false;
                if (resp.status == 0) {
                    var data = resp.data;
                    this.total = data.total;
                    this.graphicsList = data.messageList;
                    cb && cb(data.messageList);
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        filterList() {
            this.pageNo = 1;
            this.getMessageList();
        },
        //删除图文列表
        delMessage(id) {
            if (!this.menuAuthCodes.includes("M163")) {
                return;
            }
            this.$confirm("是否确定删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                delMessage({ ids: id }).then((resp) => {
                    if (resp.status == 0) {
                        this.$antMessage.success("删除成功");
                        this.getMessageList();
                        this.clearData();
                    } else {
                        this.$antMessage.warning("删除失败");
                    }
                });
            }).catch();
        },
        //添加、编辑
        saveValidate() {
            if (!this.fromClassId) {
                this.$antMessage.warning("请选择分类");
                return;
            }
            if (this.isMulti == 1) { //开启多图文
                var resultArr = []
                this.graphicsFormList.forEach((item, i) => {
                    this.graphicsIndex = i;
                    this.$nextTick(() => {
                        var result = this.$refs.graphicsForm.validate();
                        resultArr.push(result);
                    });
                });
                setTimeout(() => {
                    Promise.all(resultArr).then(() => {
                        this.submit();
                    }).catch(() => {
                        this.$antMessage.warning("请完善图文信息");
                    });
                }, 1000);
            } else {
                this.$refs.graphicsForm.validate((valid) => {
                    if (valid) {
                        this.submit();
                    } else {
                        this.$antMessage.warning("请完善图文信息");
                    }
                });
            }
        },
        submit() {
            var contentList = this.isMulti == 1 ? this.graphicsFormList : [this.graphicsFormList[0]];
            var param = {
                coverIndex: 0,
                isMulti: this.isMulti,
                classId: this.fromClassId,
                contentList: contentList
            }
            if (this.editType == "add") {
                addMessage(param).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("添加成功");
                        this.getMessageList();
                        this.clearData();
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            } else {
                param.id = this.editId;
                editMessage(param).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("编辑成功");
                        this.getMessageList();
                        this.clearData();
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }
        },
        openAdd() {
            this.editType = "add";
            this.fromClassId = this.classId != "0" ? this.classId : null;
            this.editShow = true;
        },
        openEdit(id) {
            if (!this.menuAuthCodes.includes("M162")) {
                return;
            }
            this.editType = "edit";
            this.editShow = true;
            this.editId = id;
            this.detailLoading = true;
            this.currentIndex = this.graphicsList.findIndex(item => item.id == id);
            findMessageById({ id }).then(resp => {
                this.detailLoading = false;
                if (resp.status == 0) {
                    var data = resp.data;
                    this.fromClassId = data.classId;
                    this.isMulti = data.isMulti;
                    this.graphicsFormList = data.contentList;
                    this.$refs.graphicsTinymce.setContent(data.contentList[0].content);
                }
            });
        },
        clearData() {
            document.getElementById("uploadPic").value = "";
            this.fromClassId = null;
            this.isMulti = 0;
            this.editId = "";
            this.editShow = false;
            this.editId = "add";
            this.graphicsIndex = 0;
            this.graphicsFormList = [{ title: "", digest: "", author: "", sourceurlStatus: 0, url: "", showPic: 0, content: "", picurl: "" }];
            this.$refs.graphicsTinymce.setContent("");
            this.$nextTick(() => {
                this.$refs.graphicsForm.resetFields();
            });
        },
        clearVal() {
            this.$refs.graphicsForm.clearValidate("url");
        },
        changePageSize(val) {
            this.pageSize = val;
            this.getMessageList();
        },
        changePageNo(val) {
            this.pageNo = val;
            this.getMessageList();
        },
        questionTitle(list) {
            var title = "";
            if (list.length > 1) {
                list.forEach(item => {
                    title += item.title + ";";
                });
            } else {
                title = list[0].title;
            }
            return title;
        },
        toggleInputClick() {
            document.getElementById("uploadPic").click();
        },
        async picChange(event) {
            var file = event.target.files[0];
            if (file.size > 30 * 1024 * 1024) {
                document.getElementById("uploadPic").value = "";
                return this.$antMessage.warning("图片大小不能超过30M!");
            }
            var uuid = "uuid-" + new Date().getTime();
            var upload = await lingYanUpload(file, uuid);
            if (upload?.data?.remoteURL) {
                this.$set(this.graphicsFormList[this.graphicsIndex], 'picurl', upload.data.remoteURL);
                this.$refs.graphicsForm.clearValidate([`picurl`]);
            }
            document.getElementById("uploadPic").value = "";
        },
        delPic() {
            this.$set(this.graphicsFormList[this.graphicsIndex], 'picurl', "");
        },
        openPicSelect() {
            var param = {
                pageNo: 1,
                pageSize: 999,
                type: "picture"
            }
            getFileList(param).then(resp => {
                if (resp.status == 0) {
                    this.picList = resp.data.fileList;
                }
            })
            this.picVisible = true;
        },
        selectPic() {
            this.picVisible = false;
            this.$set(this.graphicsFormList[this.graphicsIndex], 'picurl', this.picRadio);
            this.$refs.graphicsForm.clearValidate([`picurl`]);
            this.picRadio = "";
        },
        addGraphics() {
            this.graphicsFormList.push({
                title: "",
                digest: "",
                author: "",
                sourceurlStatus: 0,
                url: "",
                showPic: 0,
                content: "",
                picurl: "",
            });
        },
        selectGraphics(i) {
            this.graphicsIndex = i;
            this.$nextTick(() => {
                this.$refs.graphicsTinymce.setContent(this.graphicsFormList[i].content);
                this.$refs.graphicsForm.clearValidate();
            });
        },
        delGraphics(i) {
            this.graphicsIndex = 1;
            this.graphicsFormList.splice(i, 1);
        },
        richTextChange() {
            this.$refs.graphicsForm.clearValidate([`content`]);
        },
        //上一个
        prev() {
            if (this.currentIndex > 0) {
                this.currentIndex -= 1;
                this.openEdit(this.graphicsList[this.currentIndex].id);
                return;
            }
            if (this.pageNo > 1) {
                this.pageNo -= 1;
                this.getMessageList((list) => {
                    this.currentIndex = list.length - 1;
                    this.openEdit(list[this.currentIndex].id);
                });
            } else if (this.pageNo == 1) {
                this.$antMessage.warning("已经是第一个了");
            }
        },
        //下一个
        next() {
            var maxPageNo = Math.ceil(this.total / this.pageSize);
            if (this.currentIndex < this.graphicsList.length - 1) {
                this.currentIndex += 1;
                this.openEdit(this.graphicsList[this.currentIndex].id);
                return;
            }
            if (this.pageNo < maxPageNo) {
                this.pageNo += 1;
                this.getMessageList((list) => {
                    this.currentIndex = 0;
                    this.openEdit(list[this.currentIndex].id);
                });
            } else if (this.pageNo == maxPageNo) {
                this.$antMessage.warning("已经是最后一个了");
            }
        }
    },
    computed: {
        graphicsForm() {
            return this.graphicsFormList[this.graphicsIndex]
        },
        ueditorConfig() {
            return ueditorConfig;
        },
        tableHeight() {
            return document.body.clientHeight - 300;
        },
    },
    components: {
        elementTable,
        Tinymce
    },
    watch: {
        classId(val) {
            this.classId = val;
            this.pageNo = 1;
            this.getMessageList();
        }
    }
}
</script>

<style lang="scss">
.graphics {
    .edui-default {
        line-height: 20px;
    }
    .graphicsList {
        .header {
            margin-bottom: 20px;
        }
    }
    .graphicsEdit {
        width: 100%;
        position: absolute;
        top: 0;
        z-index: 99;
        background: #fff;
        height: 100%;
        overflow-y: scroll;
        .header {
            margin-bottom: 30px;
            padding-right: 5px;
            > span {
                height: 30px;
                line-height: 30px;
                color: #363c43;
                font-size: 16px;
                border-left: 2px solid #6b5ee2;
                padding-left: 8px;
            }
        }
        .container {
            display: flex;
            padding-bottom: 20px;
            .editFrom {
                width: 60%;
                flex-shrink: 0;
                .inlineblock {
                    display: inline-block;
                }
                .link {
                    width: calc(100% - 160px);
                    margin-left: 20px;
                    .el-form-item__content {
                        margin-left: 0 !important;
                    }
                }
            }
            .preview {
                width: 40%;
                margin-left: 70px;
            }
        }
        .buttomBtn {
            width: 100%;
            position: absolute;
            left: 0;
            bottom: 0;
            background: #fff;
            padding-right: 5px;
            .el-button {
                margin-left: 20px;
            }
        }
        .bold {
            font-size: 14px;
            color: #363c43;
            font-weight: bold;
        }
        .delPic {
            margin-left: 20px;
            color: #fe6470;
            cursor: pointer;
        }
    }
    .selectPic {
        .picList {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
            .pictureItem {
                position: relative;
                width: 100px;
                margin-bottom: 20px;
                margin-right: 40px;
                .el-radio {
                    position: absolute;
                    top: 5px;
                    right: -5px;
                    margin-right: 0;
                }
                img {
                    width: 100px;
                    height: 100px;
                    object-fit: cover;
                }
            }
        }
    }
    .graphicsPreview {
        margin-top: 20px;
        padding: 0 20px;
        .graphicsItem {
            position: relative;
            height: 150px;
            padding: 15px;
            border: 1px dashed #dae1e9;
            border-radius: 6px;
            .el-image {
                width: 100%;
                height: 100%;
                .image-slot {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: #f5f7fa;
                    > i {
                        font-size: 30px;
                    }
                }
            }
            .title {
                padding-left: 10px;
                width: calc(100% - 30px);
                position: absolute;
                bottom: 15px;
                left: 15px;
                color: #fff;
                background: linear-gradient(transparent, rgba(0, 0, 0, 0.4));
                height: 30px;
                line-height: 30px;
                padding: 0 10px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }
    }
    .isMulti.graphicsPreview {
        .graphicsItem:hover .delIcon {
            display: block;
        }
        .active.graphicsItem {
            border-color: #6b5ee2;
        }
        .delIcon {
            position: absolute;
            top: 20px;
            right: 20px;
            font-size: 20px;
            color: #b7c1c9;
            cursor: pointer;
            display: none;
        }
        .addGraphics {
            display: flex;
            align-items: center;
            justify-content: center;
            .iconfont {
                font-size: 30px;
                color: #b7c1c9;
                cursor: pointer;
            }
        }
    }
    .icon-yulan {
        font-size: 24px;
        padding: 5px;
        background: #f5f7fa;
        border-radius: 6px;
        color: #b7c1c9;
        margin-left: 10px;
        position: relative;
        top: 4px;
        &:hover {
            background: #eaeef4;
            color: #abb4bc;
        }
    }
}
</style>